package com.dingup.paike.service.pk.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingup.api.Util.DateUtil;
import com.dingup.api.adapter.classInfo.ClassInfoAdapter;
import com.dingup.api.adapter.user.SysUserAdapter;
import com.dingup.api.bean.page.PageData;
import com.dingup.api.bean.response.SelectBean;
import com.dingup.api.model.classInfo.ClassInfo;
import com.dingup.api.model.classInfo.ClassUserInfo;
import com.dingup.paike.adapter.pk.PkLessonInfoAdapter;
import com.dingup.paike.adapter.pk.PkLessonUpdateLogAdapter;
import com.dingup.paike.adapter.pk.PkLessonUserAdapter;
import com.dingup.paike.bean.requestBean.pk.PkLessonInfoRequestBean;
import com.dingup.paike.bean.requestBean.pk.PkLessonInfoSaveBatchRequestBean;
import com.dingup.paike.bean.requestBean.pk.PkLessonInfoScreenPageBean;
import com.dingup.paike.dao.*;
import com.dingup.paike.enums.PkLessonUserTypeEnum;
import com.dingup.paike.feign.client.classInfo.ClassInfoFeignClient;
import com.dingup.paike.feign.client.user.UserFeignClient;
import com.dingup.paike.model.pk.PkLessonInfo;
import com.dingup.paike.model.pk.PkLessonUser;
import com.dingup.paike.model.pk.PkUserInfo;
import com.dingup.paike.model.pk.PkVideoInfo;
import com.dingup.paike.service.pk.PkClassInfoService;
import com.dingup.paike.service.pk.PkLessonInfoService;
import com.dingup.paike.util.EEOUtil;
import com.dingup.paike.util.OSSUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.suyeer.basic.util.BDateUtil;
import com.suyeer.basic.util.BLogUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

import static com.dingup.paike.util.ConstUtil.*;

/**
 * Created by wancheng on 2018/9/27.
 */
@Service
public class PkLessonInfoServiceImpl implements PkLessonInfoService {

    private static Logger logger = LoggerFactory.getLogger(PkLessonInfoServiceImpl.class);

    private final String TIME_DEFAULT_FULLY = "yyyy-MM-dd HH:mm";

    private final String[] DATE_PATTERN_ARR = {"昨天 HH:mm", "今天 HH:mm", "明天 HH:mm", "后天 HH:mm", "yyyy-MM-dd HH:mm"};

    @Autowired
    PkLessonInfoMapper pkLessonInfoMapper;
    @Autowired
    PkLessonUserMapper pkLessonUserMapper;
    @Autowired
    UserFeignClient userFeignClient;
    @Autowired
    ClassInfoFeignClient classInfoFeignClient;
    @Autowired
    PkClassInfoMapper pkClassInfoMapper;
    @Autowired
    PkUserInfoMapper pkUserInfoMapper;
    @Autowired
    PkClassInfoService pkClassInfoService;

    @Autowired
    private PkVideoInfoMapper pkVideoInfoMapper;

    /**
     * 排课保存  保存前要checktime一下
     *
     * @param pkLessonInfoRequestBean
     * @return
     */
    @Override
    @Transactional
    public PkLessonInfo save(PkLessonInfoRequestBean pkLessonInfoRequestBean) throws Exception {
        PkLessonInfo pkLessonInfo = pkLessonInfoRequestBean.getPkLessonInfo();
        ClassInfo classInfo = classInfoFeignClient.getSimpleClassInfo(pkLessonInfo.getClassId());
        //课节名称
        String pkLessonName = String.format("%s-%s-%s",
                classInfo.getClassName(),
                pkLessonInfoRequestBean.getSubjectName(),
                DateUtil.date2Str(pkLessonInfo.getBeginTime(), "MMdd"));
        pkLessonInfo.setLessonName(pkLessonName);
        pkLessonInfo.setIfDelete(false);
        //非强制排课
        if (pkLessonInfoRequestBean.getIfArrangeLessonForce() != null && !pkLessonInfoRequestBean.getIfArrangeLessonForce()) {
            checkTime(pkLessonInfoRequestBean, pkLessonInfo);
        }
        if (!pkLessonInfo.getIfPreLesson() && pkLessonInfoRequestBean.getIfSyncEeo()) {
            syncEEO(pkLessonInfoRequestBean, classInfo, pkLessonInfo, null);
        }
        pkLessonInfoMapper.insertSelective(pkLessonInfo);
        //老师
        if (!StringUtils.isEmpty(pkLessonInfoRequestBean.getTeacherId())) {
            PkLessonUser teacher = new PkLessonUser();
            String teacherName = userFeignClient.getUserNameByUserId(pkLessonInfoRequestBean.getTeacherId());
            teacher.setCreateTime(new Date());
            teacher.setPkLessonId(pkLessonInfo.getId());
            teacher.setUserId(pkLessonInfoRequestBean.getTeacherId());
            teacher.setUserName(teacherName);
            teacher.setType(PkLessonUserTypeEnum.TEACHER);
            pkLessonUserMapper.insertSelective(teacher);
        }
        //学生
        List<String> studentList = Arrays.asList(pkLessonInfoRequestBean.getStudentIds());
        if (!CollectionUtils.isEmpty(studentList)) {
            studentList.forEach(
                    s -> {
                        PkLessonUser student = new PkLessonUser();
                        String studentName = userFeignClient.getUserNameByUserId(s);
                        student.setCreateTime(new Date());
                        student.setPkLessonId(pkLessonInfo.getId());
                        student.setUserId(s);
                        student.setUserName(studentName);
                        student.setType(PkLessonUserTypeEnum.STUDENT);
                        pkLessonUserMapper.insertSelective(student);
                    }
            );
        }
        //旁听

        if (pkLessonInfoRequestBean.getObserverIds() != null) {
            List<String> listenAttendList = Arrays.asList(pkLessonInfoRequestBean.getObserverIds());
            listenAttendList.stream().forEach(
                    s -> {
                        PkLessonUser user = new PkLessonUser();
                        String userName = userFeignClient.getUserNameByUserId(s);
                        user.setCreateTime(new Date());
                        user.setPkLessonId(pkLessonInfo.getId());
                        user.setUserId(s);
                        user.setUserName(userName);
                        user.setType(PkLessonUserTypeEnum.OBSERVER);
                        pkLessonUserMapper.insertSelective(user);
                    }
            );
        }
        return pkLessonInfo;
    }

    @Override
    public Boolean checkTime(PkLessonInfoRequestBean pkLessonInfoRequestBean, PkLessonInfo pkLessonInfo) throws InvalidCipherTextException {
        //检查老师或学生或旁听是否和其他课程冲突
        List<String> members = new ArrayList<>();
        if (pkLessonInfoRequestBean.getTeacherId() != null) {
            members.addAll(Arrays.asList(pkLessonInfoRequestBean.getTeacherId()));
        }
        if (pkLessonInfoRequestBean.getStudentIds() != null) {
            members.addAll(Arrays.asList(pkLessonInfoRequestBean.getStudentIds()));
        }
        if (pkLessonInfoRequestBean.getObserverIds() != null) {
            members.addAll(Arrays.asList(pkLessonInfoRequestBean.getObserverIds()));
        }
        List<PkLessonUserAdapter> userAdapters = pkLessonUserMapper
                .getPkUserLeftJoinPkLesson(members,
                        pkLessonInfo.getBeginTime(),
                        pkLessonInfo.getEndTime(),
                        pkLessonInfoRequestBean.getId());
        if (!CollectionUtils.isEmpty(userAdapters)) {
            StringBuilder message = new StringBuilder("该课节不在");
            String data = userAdapters.stream().map(PkLessonUserAdapter::getUserName).distinct().collect(Collectors.joining(","));
            message.append(data);
            message.append("的可用时间内");
            throw new InvalidCipherTextException(message.toString());
        }
        return true;
    }

    /**
     * User: jun
     * Date: 2018/10/9
     * Desc: 同步课节信息到eeo, 要先检查班级是否已同步到eeo, 然后检查学生是否同步到EEO,
     * 如果没有同步, 需要先同步班级和用户数据到EEO
     */
    private void syncEEO(PkLessonInfoRequestBean pkLessonInfoRequestBean,
                         ClassInfo classInfo, PkLessonInfo pkLessonInfo, Integer eeoLessonId) throws Exception {
        Integer eeoCourseId = getEeoCourseId(classInfo);
        checkMember(pkLessonInfoRequestBean, eeoCourseId);
        SysUserAdapter teacherInfo = userFeignClient.getUserByUserId(pkLessonInfo.getTeacherId());
        String telephone = getTelephone(teacherInfo);
        pkLessonInfo.setEeoCourseId(eeoCourseId);
        pkLessonInfo.setEeoLessonId(eeoLessonId);
        // 添加/更新课节到eeo
        if (eeoLessonId == null || eeoLessonId.equals(0)) {
            eeoLessonId = EEOUtil.addCourseClass(pkLessonInfo, eeoCourseId, telephone, teacherInfo.getUserName());
            pkLessonInfo.setEeoLessonId(eeoLessonId);
        } else {
            EEOUtil.editCourseClass(pkLessonInfo, telephone, teacherInfo.getUserName());
            EEOUtil.modifyClassSeatNum(pkLessonInfo);
        }
    }

    /**
     * 检查课程的相关人员
     *
     * @param pkLessonInfoRequestBean PkLessonInfoRequestBean
     * @param eeoCourseId             Integer
     * @throws Exception Exception
     */
    private void checkMember(PkLessonInfoRequestBean pkLessonInfoRequestBean, Integer eeoCourseId) throws Exception {
        // 检查老师是否注册
        checkAndSaveEeoUserInfo(pkLessonInfoRequestBean.getTeacherId());
        // 检查学生是否注册
        for (String s : pkLessonInfoRequestBean.getStudentIds()) {
            checkAndSaveEeoUserInfo(s);
        }
        // 检查旁听是否注册
        if (pkLessonInfoRequestBean.getObserverIds() != null) {
            for (String s : pkLessonInfoRequestBean.getObserverIds()) {
                checkAndSaveEeoUserInfo(s);
            }
            // 旁听添加到EEO班级
            JSONArray studentArr = new JSONArray();
            for (String s : pkLessonInfoRequestBean.getObserverIds()) {
                SysUserAdapter sysUserAdapter = userFeignClient.getUserByUserId(s);
                String telephone = getTelephone(sysUserAdapter);
                JSONObject studentObj = new JSONObject();
                studentObj.put(KEY_ACCOUNT, telephone);
                studentObj.put(KEY_NAME, sysUserAdapter.getUserName());
                studentArr.add(studentObj);
            }
            EEOUtil.addCourseStudentMultiple(studentArr, eeoCourseId, CODE_OBSERVER);
        }
    }

    private Integer getEeoCourseId(ClassInfo classInfo) throws Exception {
        Integer eeoCourseId = pkClassInfoMapper.getEeoCourseIdByClassId(classInfo.getId());
        if (eeoCourseId == null || eeoCourseId.equals(0)) {
            // 创建EEO班级
            eeoCourseId = pkClassInfoService.addClassAndSyncEEO(classInfo);
        }
        return eeoCourseId;
    }

    @Override
    public void checkAndSaveEeoUserInfo(String userId) throws Exception {
        if (!pkUserInfoMapper.exist(userId)) {
            SysUserAdapter sysUserAdapter = userFeignClient.getUserByUserId(userId);
            String telephone = getTelephone(sysUserAdapter);
            JSONObject retObj = EEOUtil.register(telephone);
            PkUserInfo pkUserInfo = new PkUserInfo();
            pkUserInfo.setUserId(userId);
            pkUserInfo.setEeoUserId(retObj.getInteger(KEY_DATA));
            pkUserInfo.setUserName(sysUserAdapter.getUserName());
            pkUserInfo.setMobile(telephone);
            pkUserInfo.setIfDelete(false);
            pkUserInfoMapper.add(pkUserInfo);
            if (!sysUserAdapter.getIfStudent()) {
                EEOUtil.registerTeacher(sysUserAdapter.getUserName(), telephone);
            }
        }
    }

    @Override
    public String getLoginLinked(String userId, Integer lessonId) throws Exception {
        SysUserAdapter sysUserAdapter = userFeignClient.getUserByUserId(userId);
        PkLessonInfo pkLessonInfo = pkLessonInfoMapper.getPkLessonInfoForFully(lessonId);
        String telephone = getTelephone(sysUserAdapter);
        return EEOUtil.getLoginLinked(pkLessonInfo, telephone);
    }

    @Override
    @Transactional
    public PkLessonInfo update(PkLessonInfoRequestBean pkLessonInfoRequestBean) throws Exception {
        logger.info("修改课节,param={}", JSON.toJSONString(pkLessonInfoRequestBean));
        PkLessonInfo pkLessonInfo = pkLessonInfoRequestBean.getPkLessonInfo();
        PkLessonInfoAdapter oldPkLessonInfo = pkLessonInfoMapper.getPkLessonInfoForFully(pkLessonInfo.getId());
        ClassInfo classInfo = classInfoFeignClient.getSimpleClassInfo(pkLessonInfo.getClassId());
        //课节名称
        String pkLessonName = String.format("%s-%s-%s",
                classInfo.getClassName(),
                pkLessonInfoRequestBean.getSubjectName(),
                DateUtil.date2Str(pkLessonInfo.getBeginTime(), "MMdd"));
        pkLessonInfo.setLessonName(pkLessonName);
        //非强制排课
        if (pkLessonInfoRequestBean.getIfArrangeLessonForce() != null && !pkLessonInfoRequestBean.getIfArrangeLessonForce()) {
            checkTime(pkLessonInfoRequestBean, pkLessonInfo);
        }
        // 同步EEO
        if (!pkLessonInfo.getIfPreLesson() && pkLessonInfoRequestBean.getIfOnlineLesson()) {
            logger.info("修改课节,同步eeo...");
            syncEEO(pkLessonInfoRequestBean, classInfo, pkLessonInfo, oldPkLessonInfo.getEeoLessonId());
        }
        pkLessonInfoMapper.updateByPrimaryKeySelective(pkLessonInfo);
        PkLessonUpdateLogAdapter updateLogAdapter = new PkLessonUpdateLogAdapter(pkLessonInfo);

        //原数据课节相关人员进行分组
        Map<PkLessonUserTypeEnum, List<PkLessonUser>> map = oldPkLessonInfo.getUsers().stream().collect(Collectors.groupingBy(PkLessonUser::getType));
        logger.info("课节人员分组...{}", JSONObject.toJSONString(map));
        if (!CollectionUtils.isEmpty(map.get(PkLessonUserTypeEnum.TEACHER))) {
            PkLessonUser teacher = map.get(PkLessonUserTypeEnum.TEACHER).get(0);
            if (!pkLessonInfo.getTeacherId().equals(teacher.getUserId())) {
                String teacherName = userFeignClient.getUserNameByUserId(pkLessonInfoRequestBean.getTeacherId());
                teacher.setUserName(teacherName);
                teacher.setUserId(pkLessonInfo.getTeacherId());
                pkLessonUserMapper.updateByPrimaryKeySelective(teacher);
                updateLogAdapter.setUpdateTeacher(teacher);
                logger.info("老师修改中...teacher={}", JSONObject.toJSONString(teacher));
            }
        } else {
            if (!StringUtils.isEmpty(pkLessonInfo.getTeacherId())) {
                PkLessonUser teacher = new PkLessonUser();
                String teacherName = userFeignClient.getUserNameByUserId(pkLessonInfoRequestBean.getTeacherId());
                teacher.setUserName(teacherName);
                teacher.setUserId(pkLessonInfo.getTeacherId());
                teacher.setCreateTime(new Date());
                teacher.setPkLessonId(pkLessonInfo.getId());
                teacher.setType(PkLessonUserTypeEnum.TEACHER);
                pkLessonUserMapper.insertSelective(teacher);
                updateLogAdapter.setUpdateTeacher(teacher);
                logger.info("老师修改中-添加...teacher={}", JSONObject.toJSONString(teacher));
            }
        }
        List<PkLessonUser> students = map.get(PkLessonUserTypeEnum.STUDENT);
        logger.info("学生修改中...");
        Map<String, List<PkLessonUser>> updateStudent = updatePkLessonUser(students, pkLessonInfoRequestBean.getStudentIds(), pkLessonInfo.getId(), PkLessonUserTypeEnum.STUDENT);
        updateLogAdapter.setUpdateStudent(updateStudent);
        List<PkLessonUser> observers = map.get(PkLessonUserTypeEnum.OBSERVER);
        logger.info("旁听人修改中...");
        Map<String, List<PkLessonUser>> updateObserver = updatePkLessonUser(observers, pkLessonInfoRequestBean.getObserverIds(), pkLessonInfo.getId(), PkLessonUserTypeEnum.OBSERVER);
        updateLogAdapter.setUpdateObserver(updateObserver);
        return updateLogAdapter;
    }

    private Map<String, List<PkLessonUser>> updatePkLessonUser(List<PkLessonUser> oldObjs, String[] newIds, Integer pkLessonId, PkLessonUserTypeEnum type) {
        if (oldObjs == null) {
            oldObjs = new ArrayList<>();
        }
        List<String> newIdsList = new ArrayList<>();
        if (newIds != null) {
            newIdsList = Arrays.asList(newIds);
        }
        List<String> oldIds = oldObjs.stream().map(PkLessonUser::getUserId).collect(Collectors.toList());
        Map<String, PkLessonUser> lessonUserMap = oldObjs.stream().collect(Collectors.toMap(PkLessonUser::getUserId, p -> p));
        //需要新增的信息
        List<PkLessonUser> addList = new ArrayList<>();
        newIdsList.stream().filter(s -> !oldIds.contains(s)).forEach(
                s -> {
                    PkLessonUser pkLessonUser = new PkLessonUser();
                    String userName = userFeignClient.getUserNameByUserId(s);
                    pkLessonUser.setCreateTime(new Date());
                    pkLessonUser.setPkLessonId(pkLessonId);
                    pkLessonUser.setUserId(s);
                    pkLessonUser.setUserName(userName);
                    pkLessonUser.setType(type);
                    pkLessonUserMapper.insertSelective(pkLessonUser);
                    addList.add(pkLessonUser);
                }
        );
        logger.info("修改课时,人员新增:{}", JSONObject.toJSONString(addList));
        //需要删除的信息
        List<PkLessonUser> deleteList = new ArrayList<>();
        List<String> finalNewIdsList = newIdsList;
        oldIds.stream().filter(s -> {
            return !finalNewIdsList.contains(s);
        }).forEach(
                s -> {
                    PkLessonUser needDelete = lessonUserMap.get(s);
                    pkLessonUserMapper.deleteByPrimaryKey(needDelete.getId());
                    deleteList.add(needDelete);
                }
        );
        logger.info("修改课时,人员删除:{}", JSONObject.toJSONString(deleteList));
        Map<String, List<PkLessonUser>> updateMap = new HashMap<>();
        updateMap.put("save", addList);
        updateMap.put("delete", deleteList);
        return updateMap;
    }

    @Override
    public PageData getPkLessonInfoAdapter(PkLessonInfoScreenPageBean pageBean) {
        PageHelper.startPage(pageBean.getPage(), pageBean.getRows());
        if (pageBean.getIfLessonFinish()) {
            PageHelper.orderBy("begin_time desc");
        } else {
            PageHelper.orderBy("begin_time asc");
        }
        List<PkLessonInfo> pks = pkLessonInfoMapper.getByPageBean(pageBean);
        PageInfo<PkLessonInfo> pageInfo = new PageInfo<>(pks);
        List<PkLessonInfo> res = pageInfo.getList();
        List<PkLessonInfoAdapter> adapters = new ArrayList<>();
        res.forEach(
                p -> {
                    PkLessonInfoAdapter a = JSONObject.parseObject(JSONObject.toJSONString(p), PkLessonInfoAdapter.class);
                    List<PkLessonUser> teacher = pkLessonUserMapper.getPkLessonUserByPkLessonIdAndType(p.getId(), PkLessonUserTypeEnum.TEACHER);
                    List<PkLessonUser> student = pkLessonUserMapper.getPkLessonUserByPkLessonIdAndType(p.getId(), PkLessonUserTypeEnum.STUDENT);
                    if (!CollectionUtils.isEmpty(teacher)) {
                        a.setTeacherName(teacher.get(0).getUserName());
                    }
                    List<String> studentNames = new ArrayList<String>();
                    if (!CollectionUtils.isEmpty(student)) {

                        student.forEach(
                                s -> {
                                    studentNames.add(s.getUserName());
                                }
                        );
                    }
                    a.setStudentNames(studentNames);
                    if (a.getBeginTime() != null) {
                        a.setIfCouldDelete(true);
                        a.setBeginTimeString(formatTime(a.getBeginTime()));
                        //上课前20分钟不能进行修改删除
                        Date currentDate = new Date();
                        if (a.getIfLessonFinish()) {
                            a.setIfCouldDelete(false);
                        }
                        if (a.getIfPreLesson()) {
                            a.setIfCouldDelete(true);
                        }

                    }
                    if (a.getEndTime() != null) {
                        String end = formatTime(a.getEndTime());
                        a.setEndTimeString(end.substring(end.length() - 5, end.length()));
                    }
                    a.clean();
                    adapters.add(a);
                }
        );
        PageData data = new PageData(pageBean.getPage(), pageBean.getRows(), adapters, pageInfo.getTotal(), pageInfo.getPages());

        return data;
    }

    @Override
    public PkLessonInfoAdapter getPkLessonInfoAdapter(Integer id) {
        PkLessonInfoAdapter adapter = pkLessonInfoMapper.getPkLessonInfoForFully(id);
        ClassInfoAdapter classInfo = classInfoFeignClient.getClassInfoById(adapter.getClassId());
        List<ClassUserInfo> classStudent = classInfo.getStudents();
        if (!CollectionUtils.isEmpty(adapter.getUsers())) {
            //根据type进行分组
            Map<PkLessonUserTypeEnum, List<PkLessonUser>> map = adapter.getUsers().stream().collect(Collectors.groupingBy(PkLessonUser::getType));
            //不需要上课的学生
            List<String> studentNotNeedGoToClass = new ArrayList<>();
            List<String> studentNames = new ArrayList<>();
            if (map.get(PkLessonUserTypeEnum.STUDENT) != null) {
                List<PkLessonUser> student = map.get(PkLessonUserTypeEnum.STUDENT);
                if (!CollectionUtils.isEmpty(student)) {
                    studentNames = student.stream().map(PkLessonUser::getUserName).collect(Collectors.toList());
                    List<String> studentIds = student.stream().map(PkLessonUser::getUserId).collect(Collectors.toList());
                    studentNotNeedGoToClass = classStudent.stream()
                            .filter(s -> !studentIds.contains(s.getUserId()))
                            .map(ClassUserInfo::getUserName)
                            .collect(Collectors.toList());
                    adapter.setStudents(studentIds);
                }
            }
            adapter.setStudentNames(studentNames);
            adapter.setStudentNotNeedGoToClass(studentNotNeedGoToClass);
            String teacherName = "";
            if (map.get(PkLessonUserTypeEnum.TEACHER) != null) {
                List<SelectBean> teacher = new ArrayList<>();
                map.get(PkLessonUserTypeEnum.TEACHER).forEach(
                        s -> {
                            teacher.add(new SelectBean(s.getUserName(), s.getUserId()));
                        }
                );
                teacherName = map.get(PkLessonUserTypeEnum.TEACHER).get(0).getUserName();
                adapter.setClassHour(map.get(PkLessonUserTypeEnum.TEACHER).get(0).getClassHour());
                adapter.setTeacher(teacher);
            }
            adapter.setTeacherName(teacherName);
            if (map.get(PkLessonUserTypeEnum.OBSERVER) != null) {
                List<SelectBean> observers = new ArrayList<>();
                map.get(PkLessonUserTypeEnum.OBSERVER).forEach(
                        s -> {
                            observers.add(new SelectBean(s.getUserName(), s.getUserId()));
                        }
                );
                adapter.setObservers(observers);
            }
        }
        if (adapter.getBeginTime() != null) {
            adapter.setBeginTimeString(DateUtil.date2Str(adapter.getBeginTime(), TIME_DEFAULT_FULLY));
        }
        if (adapter.getEndTime() != null) {
            adapter.setEndTimeString(DateUtil.date2Str(adapter.getEndTime(), TIME_DEFAULT_FULLY));
        }
        if (classInfo != null) {
            adapter.setClassName(classInfo.getClassName());
        }
        adapter.setDayTime(DateUtil.date2Str(adapter.getBeginTime(), "MM月dd日"));
        //去掉无用的数据
        adapter.userClean();
        return adapter;
    }

    /**
     * 格式化时间
     *
     * @param date
     * @return
     */
    private String formatTime(Date date) {
        int dayCalc = BDateUtil.calcDay(date, false);
        //dayCalc = dayCalc == -1 ? 3 : dayCalc;
        dayCalc = (dayCalc < -1 || dayCalc > 2) ? 3 : dayCalc;
        return DateUtil.date2Str(date, DATE_PATTERN_ARR[dayCalc + 1]);
    }

    @Override
    public List<Map<String, Integer>> getLessonCount(Boolean ifPreLesson) {
        return pkLessonInfoMapper.getLessonCount(ifPreLesson);
    }

    @Override
    /**
     * 批量删除
     */
    @Transactional
    public void deleteBatchOfLesson(Integer[] lessonIds, String operaUserId) {
        if (lessonIds != null && lessonIds.length > 0) {
            pkLessonInfoMapper.deleteBatchOfLesson(lessonIds);
            pkLessonUserMapper.deleteByPkLessonIds(Arrays.asList(lessonIds));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatchOfLesson(PkLessonInfoSaveBatchRequestBean bean, String opearUserId, Boolean ifSyncEeo) throws Exception {
        ClassInfo classInfo = classInfoFeignClient.getSimpleClassInfo(bean.getClassId());
        List<PkLessonInfo> lessonInfos = bean.getPkLessonInfoArray();
        lessonInfos.forEach(
                l -> {
                    //课节名称
                    String pkLessonName = String.format("%s-%s-%s",
                            classInfo.getClassName(),
                            bean.getSubjectName(),
                            DateUtil.date2Str(l.getBeginTime(), "MMdd"));
                    l.setLessonName(pkLessonName);
                    l.setIfDelete(false);
                    l.setEeoCourseId(0);
                    l.setEeoLessonId(0);
                    l.setCreateTime(new Date());
                    logger.info("PkLessonInfo保存... data={}", JSONObject.toJSONString(l));
                }
        );
        if (bean.getIfSyncEeo() && !bean.getIfPreLesson()) {
            syncEeoBatchOfLesson(bean, classInfo, lessonInfos);
            logger.info("同步eeo... lessonInfos={}", JSONObject.toJSONString(lessonInfos));
            //过滤没有添加成功的课节
            lessonInfos = lessonInfos.parallelStream()
                    .filter(l -> l.getEeoCourseId() != null || l.getEeoLessonId() != null)
                    .collect(Collectors.toList());
        }
        pkLessonInfoMapper.insertForBatch(lessonInfos);
        //成员list
        List<PkLessonUser> memberList = new ArrayList<>();
        Date currentDate = new Date();
        //班主任
        if (classInfo.getClassTeacher() != null) {
            PkLessonUser master = new PkLessonUser();
            master.setCreateTime(currentDate);
            master.setUserId(classInfo.getClassTeacher().getUserId());
            master.setUserName(classInfo.getClassTeacher().getUserName());
            master.setType(PkLessonUserTypeEnum.MASTER);
            memberList.add(master);
            logger.info("班主任信息... teacher={}", JSONObject.toJSONString(master));
        }
        //老师
        if (!StringUtils.isEmpty(bean.getTeacherId())) {
            PkLessonUser teacher = new PkLessonUser();
            String teacherName = userFeignClient.getUserNameByUserId(bean.getTeacherId());
            teacher.setCreateTime(currentDate);
            teacher.setUserId(bean.getTeacherId());
            teacher.setUserName(teacherName);
            teacher.setType(PkLessonUserTypeEnum.TEACHER);
            memberList.add(teacher);
            logger.info("老师信息... teacher={}", JSONObject.toJSONString(teacher));
        }
        //学生

        if (bean.getStudentIds() != null) {
            List<String> studentList = Arrays.asList(bean.getStudentIds());
            studentList.forEach(
                    s -> {
                        PkLessonUser student = new PkLessonUser();
                        String studentName = userFeignClient.getUserNameByUserId(s);
                        student.setCreateTime(currentDate);
                        student.setUserId(s);
                        student.setUserName(studentName);
                        student.setType(PkLessonUserTypeEnum.STUDENT);
                        memberList.add(student);
                        logger.info("学生信息... student={}", JSONObject.toJSONString(student));
                    }
            );
        }
        //旁听
        if (bean.getObserverIds() != null) {
            List<String> listenAttendList = Arrays.asList(bean.getObserverIds());
            listenAttendList.forEach(
                    s -> {
                        PkLessonUser user = new PkLessonUser();
                        String userName = userFeignClient.getUserNameByUserId(s);
                        user.setCreateTime(currentDate);
                        user.setUserId(s);
                        user.setUserName(userName);
                        user.setType(PkLessonUserTypeEnum.OBSERVER);
                        memberList.add(user);
                        logger.info("旁听信息... obsever={}", JSONObject.toJSONString(user));
                    }
            );
        }
        //批量添加
        List<PkLessonUser> needInsertList = new ArrayList<>();
        List<PkLessonInfo> finalLessonInfos = lessonInfos;
        memberList.forEach(
                u -> {
                    finalLessonInfos.stream().forEach(
                            l -> {
                                try {
                                    PkLessonUser user = u.clone();
                                    user.setPkLessonId(l.getId());
                                    needInsertList.add(user);
                                    logger.info("PkLessonUser添加数据... data={}", JSONObject.toJSONString(user));
                                } catch (CloneNotSupportedException e) {
                                    e.printStackTrace();
                                }
                            }
                    );
                }
        );
        if (!CollectionUtils.isEmpty(memberList)) {
            pkLessonUserMapper.insertForBatch(needInsertList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatchOfLessonMultiForm(List<PkLessonInfoSaveBatchRequestBean> beanList, String opearUserId) throws Exception {
        for (PkLessonInfoSaveBatchRequestBean bean : beanList) {
            saveBatchOfLesson(bean, opearUserId, bean.getIfSyncEeo());
        }
    }

    /**
     * 批量同步eeo
     *
     * @param bean
     * @param classInfo
     * @return
     * @throws Exception
     */
    public List<PkLessonInfo> syncEeoBatchOfLesson(PkLessonInfoSaveBatchRequestBean bean, ClassInfo classInfo, List<PkLessonInfo> lessonInfos) throws Exception {
        //检查有没有同步eeo班级
        Integer eeoCourseId = getEeoCourseId(classInfo);
        //检查成员
        checkMember(bean, eeoCourseId);
        SysUserAdapter teacherInfo = userFeignClient.getUserByUserId(bean.getTeacherId());
        String telephone = getTelephone(teacherInfo);
        JSONArray resArray = EEOUtil.addCourseClassMultiple(lessonInfos, eeoCourseId, telephone, teacherInfo.getUserName());
        for (int i = 0; i < resArray.size(); i++) {
            Integer errno = resArray.getJSONObject(i).getInteger(KEY_ERRNO);
            if (errno != null && errno.intValue() == 1) {
                Integer eeoLessonId = resArray.getJSONObject(i).getInteger(KEY_DATA);
                if (eeoLessonId != null) {
                    lessonInfos.get(i).setEeoLessonId(eeoLessonId);
                    lessonInfos.get(i).setEeoCourseId(eeoCourseId);
                    logger.info("课程与eeo数据组合... data={}", JSONObject.toJSONString(lessonInfos.get(i)));
                }
            }
        }
        return lessonInfos;
    }

    private String getTelephone(SysUserAdapter sysUserAdapter) {
        String telephone = sysUserAdapter.getMobile();
        if (telephone.startsWith(CHINA_CODE)) {
            telephone = sysUserAdapter.getUserAccount();
        }
        return telephone;
    }

    @Override
    public void initVideoInfo(PkLessonInfoAdapter pkLessonInfoAdapter) {
        try {
            if (pkLessonInfoAdapter.getIfSyncEeo()) {
                JSONObject videoUrlObj = EEOUtil.getWebcastUrl(pkLessonInfoAdapter);
                JSONObject videoDownloadObj = EEOUtil.getClassVideo(pkLessonInfoAdapter);
                if (videoDownloadObj != null && !videoDownloadObj.containsKey("mp4List")) {
                    PkVideoInfo pkVideoInfo = pkVideoInfoMapper.getByLessonId(pkLessonInfoAdapter.getId());
                    List<String> ossVideoUrlList = new ArrayList<>();
                    if (pkVideoInfo != null && pkVideoInfo.getIfDownload()) {
                        for (int i = 0; i < pkVideoInfo.getEeoUrlList().size(); i++) {
                            String fileName = String.format("%s_%s.mp4", pkLessonInfoAdapter.getId(), i);
                            OSSUtil.restoreFile("eeo-archive", "video/" + fileName);
                            ossVideoUrlList.add("//eeo-archive.oss-cn-beijing.aliyuncs.com/video/" + fileName);
                        }
                        pkLessonInfoAdapter.setOssVideoUrlList(ossVideoUrlList);
                    }
                }
                pkLessonInfoAdapter.setVideoUrlObj(videoUrlObj);
                pkLessonInfoAdapter.setVideoDownloadObj(videoDownloadObj);
            }
        } catch (Exception e) {
            BLogUtil.error(e);
        }
    }

    @Override
    public Integer getPkLessonCountNextDay(String userId) {
        Date concurrentDate = new Date();
        Date nextDate = DateUtils.addDays(concurrentDate, 1);
        Integer count = pkLessonInfoMapper.getPkLessonCount(userId, nextDate);
        return count;
    }

    @Override
    @Transactional
    public void deletePkLessonByClass(Integer classId) {
        List<PkLessonInfo> pkLessonInfos = pkLessonInfoMapper.getPkLessonByClassId(classId, new Date(), null);
        List<Integer> pkLessonIds = pkLessonInfos.stream().map(PkLessonInfo::getId).collect(Collectors.toList());
        Integer[] ids = new Integer[pkLessonIds.size()];
        pkLessonIds.toArray(ids);
        pkLessonInfoMapper.deleteBatchOfLesson(ids);
        pkLessonUserMapper.deleteByPkLessonIds(pkLessonIds);
    }
}
